package cz.uvn.orthopedy.server.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import cz.uvn.orthopedy.client.entity.Hall;

public final class HallJdo {
	
	private HallJdo() {
	}

	public static void editHall(Hall hall) {
		// // TODO
		// LoginServer login = new LoginServer();
		// User user = login.getUser();
		// if (user == null) {
		// return;
		// }

		// key = KeyFactory.createKey(MathDataJdo.class.getSimpleName(),
		// user.getEmail());
		// key = KeyFactory.createKey(HallJdo.class.getSimpleName(), "user1");

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Hall.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			query.setUnique(true);
			Hall result = (Hall) query.execute(hall.getId());
			if (result != null) {
				result.setNumber(hall.getNumber());
				result.setDescription(hall.getDescription());
			}
		} finally {
			pm.close();
		}
	}

	public static void createHall(Hall hall) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(hall);
		} finally {
			pm.close();
		}
	}
	
	public static void deleteHall(Hall hall) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Hall.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
//			query.setUnique(true);
			@SuppressWarnings("unchecked")
			List<Hall> result = (List<Hall>) query.execute(hall.getId());
			assert result.size() == 1;
			pm.deletePersistent(result.get(0));
		} finally {
			pm.close();
		}
	}

	public static Hall[] getHalls() {
		Hall[] halls = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
		try {
			Query q = pm.newQuery(Hall.class);
			q.setOrdering("number");
			@SuppressWarnings("unchecked")
			List<Hall> result = (List<Hall>) q.execute();
			halls = new Hall[result.size()];
			for (int i = 0; i < result.size(); i++) {
				Hall h = result.get(i);
				halls[i] = new Hall(h.getId(), h.getNumber(), h.getDescription());
			}
		} finally {
			pm.close();
		}
		return halls;
	}

	public static Hall getHall(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Hall.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			query.setUnique(true);
			return (Hall) query.execute(id);
		} finally {
			pm.close();
		}
	}

}
